/**
 * Created by ruiyuan on 15-12-23.
 */
var async = require('async');
var mysqlUtil = require('../common/utils/mysqlUtil');
var toolUtil = require('../common/utils/toolUtil');
var User = mongoose.model('user');
var Group = mongoose.model('group_family');
var UserInvitationRecord = mongoose.model('user_invitation_share');
var UserCommunity = mongoose.model('user_community');

exports.postUserContactsService = function (user, input, groupId, deviceId, callback) {
    var array = [];
    var data = [];
    input.contacts.forEach(function (item) {
        if (item.phone.indexOf('+86') == 0) {
            item.phone = item.phone.substr(3, item.phone.length);
        }
        item.phone = item.phone.replace(/\s+/g, "");

        array.push(item.phone);
        data.push([user._id, deviceId, item.name, item.phone, new Date().getTime()])
    });

    User.find({mobilePhone: {$in: array}}, 'mobilePhone images nickName', function (err, result) {
        if (err) return callback(err);
        async.each(result, function (temp, cb) {
            Group.findOne({_id: groupId, 'members.user': temp._id}, function (err, mem) {
                temp._doc.isAdded = false;
                if (mem != null) {
                    mem.members.forEach(function (item) {
                        if (item.user == temp._id + '' && item.status == 1) {
                            temp._doc.isAdded = true;
                        }
                    })
                }
                temp._doc.phone = temp.mobilePhone;
                cb();
            })
        }, function () {
            var res = {
               /* 宝宝树66小区二次改造    mod   张秘  20170723   start*/
                message: '我在“宝宝树66小区”创建了我们的大家庭，以后全家人的生活上的事情都可以在手机上都可以互相关照啦，你也来下载加入吧：http://t.cn/R4izR49',
               /* 宝宝树66小区二次改造    mod   张秘  20170723   end*/
                users: result
            };

            callback(null, res);

            var sql = 'insert into user_contacts (user_id,device_id,name,phone,create_time) values ? ON DUPLICATE KEY UPDATE user_id=user_id';
            mysqlUtil.query(sql, [data], function (err, result) {
                if (err) logger.error(err.message);
            });
        });
    })
};

exports.createNewFamilyService = function (user, callback) {

    Group.findOne({
        members: {$elemMatch: {user: user._id, status: 1}}
    }, function (err, group) {
        if (group != null) return callback({message: '当前小区已有家庭群组'});

        var temp = new Group();
        temp.createdBy = user._id;
        temp.community = user.community._id;
        temp.city = user.community.cityId;
        temp.members = [{user: user._id, status: 1}];
        temp.save(callback);
    });
};

exports.getGroupListService = function (user, callback) {
    Group.find({'members.user': user._id}, 'community members').populate('community', 'communityName')
        .exec(function (err, result) {

        });
};

exports.getGroupInfoService = function (user, groupId, callback) {
    Group.findOne({
        _id: groupId,
        members: {$elemMatch: {user: user._id, status: 1}}
    }, 'community members').populate('community', 'communityName')
        .populate('members.user', 'nickName images mobilePhone huanxinUserName')
        .exec(function (err, result) {
            if (result != null) {
                var data = {
                    groupName: result.community.communityName + '的家',
                    members: result.members
                };
                callback(err, data);
            } else {
                callback(null, {groupName: '', members: []});
            }
        })
};


exports.confirmToJoinService = function (user, input, callback) {

    Group.findOne({
        members: {$elemMatch: {user: user._id, status: 1}}
    }, function (err, group) {
        if (group != null) {
            exports.quitFamilyService(user._id, group._id, function () {
            })
        }
        Group.update({_id: input.groupId, 'members.user': user._id}, {
            'members.$.status': 1,
            'members.$.joinDate': new Date()
        }, function (err, result) {
            callback();
            //UserCommunity.findOne({user: user._id, community: input.communityId}, function (err, comm) {
            //    if (comm == null) {
            //        var temp = new UserCommunity();
            //        temp.user = user._id;
            //        temp.community = input.communityId;
            //        temp.save();
            //    }
            //});
        })
    });
};

exports.registerJoinGroupService = function (userId, groupId, inviter) {
    Group.update({_id: groupId}, {$push: {members: {user: userId, status: 1}}}).exec();

    toolUtil.putMessageBusinessMQ({
        msgType: 'group_join',
        toUserId: inviter,
        userId: userId,
        groupId: groupId
    })
};


exports.quitFamilyService = function (userId, groupId, callback) {
    Group.update({_id: groupId}, {$pull: {members: {user: userId}}}, function (err, result) {
        callback(err, result);

        toolUtil.putMessageBusinessMQ({
            msgType: 'group_quit',
            userId: userId,
            groupId: groupId
        });

        Group.findOne({_id: groupId}, 'createdBy members', function (err, group) {
            if (group != null && group.createdBy + '' == userId && group.members.length > 0) {
                Group.update({_id: groupId}, {createdBy: group.members[0].user}).exec();
            }
        })
    });
};


exports.inviteUserService = function (userId, body, callback) {
    async.series([
        function (callbackInner) {
            Group.findOne({_id: body.groupId, 'members.user': body.userId}, function (err, result) {
                if (result == null) {
                    Group.update({_id: body.groupId}, {$push: {members: {user: body.userId, status: 0}}}, callbackInner)
                } else {
                    callbackInner();
                }
            })
        },
        function (callbackInner) {
            toolUtil.putMessageBusinessMQ({
                msgType: 'invite_family_group',
                groupId: body.groupId,
                userId: userId,
                toUserId: body.userId
            });
            callbackInner();
        }
    ], callback)
};

exports.recordInviteService = function (user, input, query, callback) {
    var temp = new UserInvitationRecord();
    temp.inviter = user._id;
    temp.phone = input.phone;
    temp.groupId = input.groupId;
    temp.type = input.type;
    temp.os = query.type;
    temp.save(function (err, result) {
        callback()
    })
};

exports.getInviteInfoService = function (groupId, inviter, user, callback) {
    async.series([
        function (callbackInner) {
            Group.findOne({_id: groupId}, 'community members').populate('community', 'communityName')
                .exec(callbackInner)
        },
        function (callbackInner) {
            User.findOne({_id: inviter}, 'nickName mobilePhone', callbackInner)
        }
    ], function (err, result) {
        var community = result[0].community;
        var message = community.communityName + '的' + result[1].nickName;
        if (result[1].mobilePhone != null) {
            message += '(' + result[1].mobilePhone + ')'
        }
        var data = {
            groupName: community.communityName + '的家',
            message: message,
            communityId: community._id,
            communityName: community.communityName,
            groupId: result[0]._id,
            status: 2,
            isSwitch: false
        };

        result[0].members.forEach(function (item) {
            if (item.user + '' == user._id) {
                data.status = item.status
            }
        });
        Group.findOne({
            members: {$elemMatch: {user: user._id, status: 1}}
        }, function (err, group) {
            data.isQuit = group != null;
            callback(err, data);
        });
    })
};